//
//  QYSearchDetaiViewController.m
//  QingYue
//
//  Created by Lei_Zhong_Xun on 2017/6/28.
//  Copyright © 2017年 com.lanou.product_A. All rights reserved.
//

#import "QYSearchDetaiViewController.h"
#import "QYSearchDetailTableViewCell.h"
#import "QYSearchView.h"
#import "QYSearchDetailModel.h"

static const CGFloat kBtnHeight = 30.f;
static NSString *const QYSearchDetailTableViewCellID = @"QYSearchDetailTableViewCell";

@interface QYSearchDetaiViewController ()<UITableViewDelegate, UITableViewDataSource>
/** 列表*/
@property (nonatomic,strong) UITableView* listTableview;
@property (nonatomic, strong) QYSearchView *searchView;
/** 列表数组*/
@property (nonatomic,strong) NSMutableArray* DataArray;

@end

@implementation QYSearchDetaiViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:self.searchView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_searchView removeFromSuperview];
    _searchView = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self subviewsInView];
}


- (void)setKeyWord:(NSString *)keyWord
{
    _keyWord = keyWord;
    [self loadData];
}

//搜索按钮的方法(每次搜索的时候, 重新搜索)
- (void)rightBarButtonPressed:(id)sender
{
    if ([_searchView.searchTfx.text length] > 0) {
        _DataArray = [NSMutableArray array];
        [SVProgressHUD showWithStatus:@"正在搜索"];
        NSDictionary *param = @{@"username":[kUserDefaults objectForKey:@"username"],
                                @"condition":_searchView.searchTfx.text};
        [[YCRequestDataService sharedManager] Post:@"GetBooks" parameters:param success:^(id response) {
            if ([response[@"Code"] isEqualToString:@"成功"]) {
                [response[@"newsList"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    QYSearchDetailModel *model = [[QYSearchDetailModel alloc] initWithDataDic:obj];
                    [_DataArray addObject:model];
                }];
                [_listTableview reloadData];
            } else {
                kTimeAfter(1, ^{kShowNet(response[@"Exception"]);});
                [SVProgressHUD dismissWithDelay:0.35];

            }
        } failure:^{
            kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
            
        }];

    }
}

#pragma mark - 数据加载
- (void)loadData
{
    _DataArray = [NSMutableArray array];
    [SVProgressHUD showWithStatus:@"正在搜索"];
    NSDictionary *param = @{@"username":[kUserDefaults objectForKey:@"username"],
                            @"condition":_keyWord};
    NSLog(@"%@", param);
    [[YCRequestDataService sharedManager] Post:@"GetBooks" parameters:param success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            [SVProgressHUD dismissWithDelay:0.35];
            [response[@"newsList"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                QYSearchDetailModel *model = [[QYSearchDetailModel alloc] initWithDataDic:obj];
                [_DataArray addObject:model];
            }];
            [_listTableview reloadData];
        } else {
            kTimeAfter(1, ^{kShowNet(response[@"Exception"]);});
            [SVProgressHUD dismissWithDelay:0.35];
        }
    } failure:^{
        kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
        
    }];
}



#pragma mark - tableview delegate and dataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QYSearchDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:QYSearchDetailTableViewCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.detailModel = _DataArray[indexPath.row];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _DataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}


#pragma mark - subviews
- (void)subviewsInView {
    
    [self showRightButtonWithTitle:@"搜索" titleColor:RGB(47, 202, 103, 1)];
    
    [self.view addSubview:self.listTableview];
    
    [_listTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(self.view);
    }];
    
}

#pragma mark - lazy load
- (UITableView *)listTableview
{
    if (!_listTableview) {
        _listTableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _listTableview.delegate = self;
        _listTableview.dataSource  = self;
        _listTableview.backgroundColor = [UIColor whiteColor];
        _listTableview.estimatedSectionFooterHeight = 0.0f;
        _listTableview.estimatedSectionHeaderHeight = 0.0f;
        _listTableview.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        if (@available(iOS 11.0, *)) {
            _listTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }

        [_listTableview registerClass:[QYSearchDetailTableViewCell class] forCellReuseIdentifier:QYSearchDetailTableViewCellID];
    }
    return _listTableview;
}
- (QYSearchView *)searchView {
    if (!_searchView) {
        _searchView = [[QYSearchView alloc] initWithFrame:CGRectMake(0, 0, 0.68*MSSize_Width, kBtnHeight)];
        _searchView.center = CGPointMake(self.view.center.x, 22);
        _searchView.backgroundColor = RGB(237, 238, 239, 1);
        _searchView.layer.cornerRadius = 5;
        _searchView.layer.masksToBounds = YES;
    }
    return _searchView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
